<template>
  <!-- 后台用户页面 -->
  <div>
    <el-card>
    <!-- 模糊查框 添加按钮 -->
    <div class="abvoeBox">
        用户名称:<el-input placeholder="请输入内容" v-model="userName" class="abvoeBox_input"></el-input>
        <el-button type="primary" @click="selectUserBackEntity()" style="margin-left:10px">查询</el-button>
        <el-button type="success" @click="openSaveUserDialogVisible()">添加</el-button>
    </div>
    <!-- 全查数据 -->
    <div class="belowBox">
       <el-table
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
            fixed
            prop="loginName"
            label="登录名称">
            <template slot-scope="scope">
                <p style="text-decoration:underline;">{{scope.row.loginName}}</p>
            </template>
            </el-table-column>
            <el-table-column
            prop="userName"
            label="用户名称">
            </el-table-column>
            <el-table-column
            prop="sex"
            label="性别">
            <template slot-scope="scope">
                <p>{{scope.row.sex===0?"男":"女"}}</p>
            </template>
            </el-table-column>
            <el-table-column
            prop="age"
            label="年龄">
            </el-table-column>
            <el-table-column
            prop="email"
            width="200px"
            label="邮箱">
            </el-table-column>
            <el-table-column
            prop="phone"
            label="电话">
            </el-table-column>
            <el-table-column
            prop="createTime"
            label="创建时间">
            </el-table-column>
            <el-table-column
            prop="updateTime"
            label="修改时间">
            </el-table-column>
            <el-table-column
            fixed="right"
            width="300px"
            label="操作">
            <template slot-scope="scope">
                <el-button type="primary" size="small" @click="selectUserBackEntityByOne(scope.row)">查看</el-button>
                <el-button type="danger" size="small" @click="deleteUserBackEntityById(scope.row.id)">删除</el-button>
                <el-button type="success" size="small" @click="openUpdateUserDialogVisible(scope.row)">编辑</el-button>
            </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 20px;">
        <template>
            <div class="block">
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="5"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </template>
    </div>
    <!-- 单查用户详情 -->
    <el-dialog
        title="详情"
        :visible.sync="selectUserBackDialogVisible"
        width="40%"
        >
        <el-form :model="tableDataForm" ref="ruleForm"   label-width="100px" class="demo-ruleForm" style="text-align: left;">
            <el-form-item label="登录名称" >
                <el-input v-text="tableDataForm.loginName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户名称">
                <el-input v-text="tableDataForm.userName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户性别">
                <el-input v-text="tableDataForm.sex ===0?'男':'女'" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户年龄">
                <el-input v-text="tableDataForm.age" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户电话">
                <el-input v-text="tableDataForm.phone" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户邮箱">
                <el-input v-text="tableDataForm.email" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="创建用户时间">
                <el-input v-text="tableDataForm.createTime" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="修改用户时间">
                <el-input v-text="tableDataForm.updateTime" style="width: 200px;"></el-input>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 添加弹窗 -->
    <el-dialog
        :title="title"
        :visible.sync="saveUserDialogVisible"
        :before-close="closeExpertFormDialog"
        width="40%"
        >
        <!-- form表单 -->
        <el-form :model="tableDataForm" ref="ruleForm" :rules="saveRules" label-width="100px" class="demo-ruleForm" style="text-align: left;">
            <el-form-item label="登录名称" prop="loginName">
                <el-input v-model="tableDataForm.loginName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户名称" prop="userName">
                <el-input v-model="tableDataForm.userName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户性别" prop="sex" >
                    <el-radio-group v-model="tableDataForm.sex" style="width: 200px;margin-left:10px">
                      <el-radio :label="0">男</el-radio>
                      <el-radio :label="1">女</el-radio>
                    </el-radio-group>
            </el-form-item>
            <el-form-item label="用户年龄" prop="age">
                <el-input v-model="tableDataForm.age" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户电话" prop="phone">
                <el-input v-model="tableDataForm.phone" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户邮箱" prop="email">
                <el-input v-model="tableDataForm.email" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户权限" prop="roleId">
                <el-select v-model="tableDataForm.roleId" placeholder="请选择">
                  <el-option
                    v-for="item in roleTableData"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                    :disabled="item.disabled">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="省" prop="provinceId" v-if="tableDataForm.roleId == 6">
                <el-select v-model="tableDataForm.provinceId" placeholder="请选择" @change="getProvinceId">
                  <el-option
                    v-for="item in provinceData"
                    :key="item.id"
                    :label="item.shortname"
                    :value="item.id"
                    :disabled="item.disabled">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId" v-if="tableDataForm.roleId == 6">
                <el-select v-model="tableDataForm.cityId" placeholder="请选择" @change="getCountyId">
                  <el-option
                    v-for="item in cityData"
                    :key="item.id"
                    :label="item.shortname"
                    :value="item.id"
                    :disabled="item.disabled">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="县" prop="countyId" v-if="tableDataForm.roleId == 6">
                <el-select v-model="tableDataForm.countyId" placeholder="请选择" @change="changeCountySelect">
                  <el-option
                    v-for="item in countyData"
                    :key="item.id"
                    :label="item.shortname"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
            <el-button type="primary" @click="saveUserBackEntity('ruleForm')">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 修改弹窗 -->
    <el-dialog
        :title="title"
        :visible.sync="updateUserDialogVisible"
        :before-close="closeExpertFormDialog"
        width="40%"
        >
        <!-- form表单 -->
        <el-form :model="tableDataForm" ref="ruleForm" :rules="updateRules" label-width="100px" class="demo-ruleForm" style="text-align: left;">
            <el-form-item label="登录名称" prop="loginName">
                <el-input v-model="tableDataForm.loginName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户名称" prop="userName">
                <el-input v-model="tableDataForm.userName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户性别" prop="sex" >
                    <el-radio-group v-model="tableDataForm.sex" style="width: 200px;margin-left:10px">
                      <el-radio :label="0">男</el-radio>
                      <el-radio :label="1">女</el-radio>
                    </el-radio-group>
            </el-form-item>
            <el-form-item label="用户年龄" prop="age">
                <el-input v-model="tableDataForm.age" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户电话" prop="phone">
                <el-input v-model="tableDataForm.phone" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户邮箱" prop="email">
                <el-input v-model="tableDataForm.email" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="用户权限" prop="roleId">
                <el-select v-model="tableDataForm.roleId" placeholder="请选择">
                  <el-option
                    v-for="item in roleTableData"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                    :disabled="item.disabled">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="省" prop="provinceId" v-if="tableDataForm.roleId == 6">
                <el-select v-model="tableDataForm.provinceId" placeholder="请选择" @change="getProvinceId">
                  <el-option
                    v-for="item in provinceData"
                    :key="item.id"
                    :label="item.shortname"
                    :value="item.id"
                    :disabled="item.disabled">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId" v-if="tableDataForm.roleId == 6">
                <el-select v-model="tableDataForm.cityId" placeholder="请选择" @change="getCountyId">
                  <el-option
                    v-for="item in cityData"
                    :key="item.id"
                    :label="item.shortname"
                    :value="item.id"
                    :disabled="item.disabled">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="县" prop="countyId" v-if="tableDataForm.roleId == 6">
                <el-select v-model="tableDataForm.countyId" placeholder="请选择" @change="changeCountySelect">
                  <el-option
                    v-for="item in countyData"
                    :key="item.id"
                    :label="item.shortname"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
            <el-button type="primary" @click="updateUserBackEntity('ruleForm')">确 定</el-button>
        </span>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 校验修改登录名查重
    const editCheckLoginName = (rule, value, callback) => {
      const reg = /^[A-Za-z]+$/
      // debugger
      if (value === '') {
        callback(new Error('登录名不能为空'))
      } else if (!reg.test(value) || value.length <= 4) {
        callback(new Error('4个字符以上的纯英文组成'))
      } else if (value === this.loginNameRule) {
        callback()
      } else {
        this.$axios.get('/eat-service/userBack/selectUserBackEntityByLoginName?loginName=' + value).then(res => {
          if (res.data.obj !== null) {
            callback(new Error('当前名字已存在'))
          } else {
            callback()
          }
        })
      }
    }
    // 校验添加登录名查重
    const checkLoginName = (rule, value, callback) => {
      // debugger
      const reg = /^[A-Za-z]+$/
      // console.log(value.length)
      if (value === '') {
        callback(new Error('登录名不能为空'))
      } else if (!reg.test(value) && value.length <= 4) {
        callback(new Error('4个字符以上的纯英文组成'))
      } else {
        this.$axios.get('/eat-service/userBack/selectUserBackEntityByLoginName?loginName=' + value).then(res => {
          if (res.data.obj !== null) {
            callback(new Error('当前名字已存在'))
          } else {
            callback()
          }
        })
      }
    }
    // 验证手机号
    const validatorPhone = function (phone, value, callback) {
      // 验证手机号的正则表达式
      const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/
      if (value !== '') {
        if (!reg.test(value)) {
          callback(new Error('输入正确手机号'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      // 校验登录名字
      loginNameRule: '',
      // 省id
      provinceId: '',
      // 市id
      cityId: '',
      // 县id
      countyId: '',
      // 县数据集
      countyData: [],
      // 市数据集
      cityData: [],
      // 省数据集
      provinceData: [],
      // 菜单表全查数据集
      roleTableData: [],
      // 修改表单规则
      updateRules: {
        loginName: [
          { validator: editCheckLoginName, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 0, max: 20, message: '用户名称不能为空', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择用户性别', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入用户年龄', trigger: 'blur' },
          { min: 0, max: 20, message: '用户年龄不能为空', trigger: 'blur' }
        ],
        phone: [
          { validator: validatorPhone, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'change' }
        ],
        roleId: [
          { required: true, message: '请选择用户权限', trigger: 'blur' }
        ]
      },
      // 添加表单规则
      saveRules: {
        loginName: [
          { validator: checkLoginName, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 0, max: 20, message: '用户名称不能为空', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择用户性别', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入用户年龄', trigger: 'blur' },
          { min: 0, max: 20, message: '用户年龄不能为空', trigger: 'blur' }
        ],
        phone: [
          { validator: validatorPhone, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择用户权限', trigger: 'blur' }
        ]
      },
      // 修改弹窗
      updateUserDialogVisible: false,
      // 添加弹窗
      saveUserDialogVisible: false,
      // 添加，修改弹窗时显示的名字
      title: '',
      // 单查数据集,添加数据集，修改数据集
      tableDataForm: {
        countyId: null,
        cityId: null,
        provinceId: null
      },
      // 单查后台用户弹窗
      selectUserBackDialogVisible: false,
      // 模糊查询（用户名称）
      userName: '',
      // 全查后台用户表数据集
      tableData: [],
      // 分页 （pageSize）一页展示5条数据 （pageNum）当前页
      pageRequest: {
        pageSize: 5,
        pageNum: 1
      },
      // 分页 前往第1页
      currentPage: 1,
      // 分页
      total: 0
    }
  },
  mounted () {
    // 全查全部的省数据
    this.userBackEntityProvince()
    // 全查角色权限下拉菜单
    this.selectRoleBackEntityByRoleId()
    // 全查后台用户表（模糊查用户名字）
    this.selectUserBackEntity()
  },
  methods: {
    // 选择县级下拉，进行强制刷新
    changeCountySelect () {
      // 强制进行页面刷新渲染 函数
      this.$forceUpdate()
    },
    // 获取市的id 查询县
    getCountyId (val) {
      // 将 被选中的id 赋值给 市id
      this.cityId = val
      // 清空县id
      this.tableDataForm.countyId = ''
      // 清空县数据集
      this.countyData = []
      this.getCountyList() // 根据市id 获取县信息列表
    },
    // 获取省的id 查询市
    getProvinceId (val) {
      // 将 被选中的id 赋值给 省id
      this.provinceId = val
      // 清空县id 清空县数据集
      this.tableDataForm.countyId = ''
      // 清空县数据集
      this.countyData = []
      // 清空市id 清空市数据集
      this.tableDataForm.cityId = ''
      // 市数据集
      this.cityData = []
      this.getCityList()
    },
    // 根据市id 获取县信息列表
    getCountyList () {
      this.$axios.get('/eat-service/userBack/userBackEntityCounty',
        {
          params: {
            cityId: this.cityId
          }
        }
      ).then(res => {
        this.countyData = res.data.obj
      }).catch(error => {
        console.log(error)
      })
    },
    // 根据省id 获取市的信息列表
    getCityList () {
      this.$axios.get('/eat-service/userBack/userBackEntityCity',
        {
          params: {
            provinceId: this.provinceId
          }
        }
      ).then(res => {
        this.cityData = res.data.obj
      }).catch(error => {
        console.log(error)
      })
    },
    // 查询全部的省数据
    userBackEntityProvince () {
      this.$axios.get('/eat-service/userBack/userBackEntityProvince'
      ).then(res => {
        this.provinceData = res.data.obj
      }).catch(error => {
        console.log(error)
      })
    },
    // 用户权限下拉菜单
    selectRoleBackEntityByRoleId () {
      this.$axios.get('/eat-service/roleBack/roleBackEntityByRoleId'
      ).then(res => {
        this.roleTableData = res.data.obj
        this.total = res.data.total
      }).catch(error => {
        console.log(error)
      })
    },
    // 添加点击X关闭是清空from表单数据
    closeExpertFormDialog (done) {
      this.$refs.ruleForm.resetFields()
      done()
      // done 用于关闭 Dialog
    },
    // 添加弹窗里的取消按钮 点击取消是清空from表单数据
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.updateUserDialogVisible = false
      this.saveUserDialogVisible = false
    },
    // 删除用户
    deleteUserBackEntityById (data) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/eat-service/userBack/deleteUserBackEntityById',
          {
            params: {
              id: data
            }
          }).then(res => {
          if (res.status === 200) {
            this.myMessage('success', '删除成功')
            this.selectUserBackEntity()
          } else {
            this.myMessage('warning', '删除失败')
          }
        }).catch(res => {
          this.myMessage('erroe', '删除失败，请联系管理员')
        })
      }).catch(() => {
        this.myMessage('info', '已取消删除')
      })
    },
    // 添加用户
    saveUserBackEntity (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/eat-service/userBack/saveOrUpdateUserBackEntity', this.tableDataForm
          ).then(res => {
            debugger
            if (res.data.flag === true) {
              this.myMessage('success', '恭喜你，操作成功！') // 成功提示
              this.saveUserDialogVisible = false // 关闭窗口
              this.tableDataForm = {
              }
              this.selectUserBackEntity()
            } else {
              this.myMessage('warning', res.data.obj) // 提示消息
            }
          }).catch(error => {
            console.log(error)
            this.myMessage('warning', '对不起，保存失败！')
          })
        } else {
          this.myMessage('warning', '请补全内容')
          return false
        }
      })
    },
    // 修改用户
    updateUserBackEntity (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/eat-service/userBack/saveOrUpdateUserBackEntity', this.tableDataForm
          ).then(res => {
            debugger
            if (res.data.flag === true) {
              this.myMessage('success', '恭喜你，操作成功！') // 成功提示
              this.updateUserDialogVisible = false // 关闭窗口
              this.tableDataForm = {
              }
              this.selectUserBackEntity()
            } else {
              this.myMessage('warning', res.data.obj) // 提示消息
            }
          }).catch(error => {
            console.log(error)
            this.myMessage('warning', '对不起，保存失败！')
          })
        } else {
          this.myMessage('warning', '请补全内容')
          return false
        }
      })
    },
    // 打开修改弹窗
    openUpdateUserDialogVisible (data) {
      this.title = '修改'
      this.updateUserDialogVisible = true
      this.cityId = data.cityId
      this.countyId = data.countyId
      this.getCountyList()
      this.getProvinceId()
      this.tableDataForm = JSON.parse(JSON.stringify(data))
      // this.tableDataForm = data
      this.loginNameRule = data.loginName
      if (this.tableDataForm.roleId !== 6) {
        this.tableDataForm.provinceId = ''
        this.tableDataForm.cityId = ''
        this.tableDataForm.countyId = ''
      }
    },
    // 打开添加弹窗
    openSaveUserDialogVisible () { // 打开添加弹窗
      this.title = '添加'
      this.saveUserDialogVisible = true
      this.tableDataForm = {
        id: 0,
        loginName: ''
      }
      // 清空市数据集
      this.cityData = []
      // 清空县数据集
      this.countyData = []
    },
    // 单查用户详情
    selectUserBackEntityByOne (data) {
      this.selectUserBackDialogVisible = true
      this.cityId = data.cityId
      this.countyId = data.countyId
      this.getCountyList()
      this.getProvinceId()
      this.tableDataForm = data
    },
    // 全查后台用户表（模糊查用户名字）
    selectUserBackEntity () {
      this.$axios.get('/eat-service/userBack/selectUserBackEntity',
        {
          params: {
            userName: this.userName,
            pageSize: this.pageRequest.pageSize,
            pageNum: this.pageRequest.pageNum
          }
        }
      ).then(res => {
        this.tableData = res.data.content
        this.total = res.data.total
      }).catch(error => {
        console.log(error)
      })
    },
    // 分页 每页条数
    handleSizeChange (val) {
      this.pageRequest.pageSize = val
      this.selectUserBackEntity()
    },
    // 分页 当前页
    handleCurrentChange (val) {
      this.pageRequest.pageNum = val
      this.selectUserBackEntity()
    },
    // 弹窗提示
    myMessage (type, message) {
      this.$message({
        type: type,
        message: message
      })
    }
  }
}
</script>

<style>
    .abvoeBox{
        width: 100%;
        height: 60px;
        text-align: left;
        margin-top: 5px;
    }
    .abvoeBox_input{
        width: 200px;
        height: 50px;
        margin-left: 10px;
    }
    .belowBox{
        margin-top: 20px;
    }
    .p1{
      border: none;
      background: none;
    }
    .p1:hover{
      color: #31c27c;
    }
    .span1{
      margin-left: 5px;
      color: red;
    }
</style>
